package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
//    微信登录接口
    private final static String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";


    private final WeChatProperties weChatProperties;

    private final UserMapper userMapper;

    public UserServiceImpl(WeChatProperties weChatProperties, UserMapper userMapper) {
        this.weChatProperties = weChatProperties;
        this.userMapper = userMapper;
    }

    /**
     * 微信登录
     * @param userLoginDTO 微信登录数据
     * @return 登录用户对象
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        log.info("微信登录，用户数据：{}", userLoginDTO);

        String openid = getOpenid(userLoginDTO);

        if (StringUtils.isEmpty(openid)) {
//            openid不为空，登录成功
            throw new  LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        User user = userMapper.getByOpenid(openid);
        if (user == null) {

            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }


        return user;
    }

    private String getOpenid(UserLoginDTO userLoginDTO) {
        //        发送请求获取openid
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");
        String resp = HttpClientUtil.doGet(WX_LOGIN_URL, map);

        JSONObject object = JSON.parseObject(resp);
        return object.getString("openid");
    }
}
